package cn.lysj.framework.common.utils.message;

import cn.lysj.framework.common.utils.http.HttpUtil;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.customer.util.WxAuzLoginUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.util.Map;

@Slf4j
public class TemplateMessageUtil {

    private static final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send"; // post请求,发送模板消息url

    private static final Type type = new TypeToken<Map<String, String>>() {
    }.getType();

    /*
     * @author drj
     * @date 2019-02-14 17:53
     * @Description
     */
    public static String createOrderMeasureTemplateMessageJson(String openId,String orderNumber) {
        TemplateMessageDomain templateMessage = new TemplateMessageDomain();
        templateMessage.setTouser(openId);// 接收的微信用户openID
        templateMessage.setTemplate_id("IoLLz1-6I8rdVuid5Nd4YtT44l9wKwF7bGqql2xLClM");// 订单测量通知
        templateMessage.setUrl("http://www.baidu.html");// 详情跳转链接
        templateMessage.getData().put("first", new TemplateMessagePostDataDomain("尊敬的用户，您的订单有变动："));
        templateMessage.getData().put("keyword1", new TemplateMessagePostDataDomain("")); // 订单编号/
        templateMessage.getData().put("keyword2", new TemplateMessagePostDataDomain("")); // 服务地址，电话联系
        templateMessage.getData().put("keyword3", new TemplateMessagePostDataDomain("")); // 预约时间
        templateMessage.getData().put("keyword4", new TemplateMessagePostDataDomain("")); // 工人信息
        templateMessage.getData().put("remark", new TemplateMessagePostDataDomain("请及时处理")); // 备注
        return new Gson().toJson(templateMessage);
    }


    public static boolean sendTemplateMessage(String param) {
        if (ParamUtil.isBlank(param)) {
            return false;
        }
        String resultJson = HttpUtil.sendPost(SEND_TEMPLATE_MESSAGE_URL + "?access_token=" + WxAuzLoginUtil.getAccessToken(), param);
        if (ParamUtil.isBlank(resultJson)) {
            log.error("发送模板消息请求错误:" + resultJson);
            return false;
        }
        Gson gson = new Gson();
        Map<String, String> map = gson.fromJson(resultJson, type);
        if (!map.get("errmsg").equals("ok")) {
            log.error("发送模板消息错误:" + resultJson);
            return false;
        }
        log.info("发送模板消息内容{}:" + param);
        return true;
    }


}
